<template>
  <Spin :spinning="loading1" tip="Loading...">
  <div>
    <!-- 一般车辆配件类型保修期维护 -->
    <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="4" :collapse="collapse" labelWidth="90" @filterChange="changeHandle"></TopFilter>
    <!-- table -->
    <Spin :spinning="loading" tip="导入中，请稍后...">
      <FilterTable
        ref="table"
        :columns="columns"
        :params="fetchParams"
        :fetchapi="fetchapi"
        :datakey="'records'"
        :onColumnsChange="(columns) => (this.columns = columns)"
        :onRowSelectChange="selectChange"
      >
        <template slot="controls" slot-scope="props">
                    <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add()">新增</multiuse-button>
          <multiuse-button size="small" type="primary" icon="el-icon-check" :click="qiyong.bind()" :disabled="disableds">启用</multiuse-button>
          <multiuse-button size="small" type="primary" icon="el-icon-close" :click="tingyong.bind()" :disabled="disableds">禁用</multiuse-button>

          <multiuse-button type="primary" :click="exportFileBtn.bind()">导出</multiuse-button>
          <multiuse-button size="small" type="primary" :click="downloadTemplate.bind()">下载模板</multiuse-button>
          <multiuse-button size="small" icon="el-icon-upload" @click="showImportFun()">导入</multiuse-button>
        </template>
      </FilterTable>
    </Spin>
    <BaseDialog :visible.sync="visible" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <Vehicle @close="close" @save="save"></Vehicle>
    </BaseDialog>
    <BaseDialog
      :visible.sync="visibleAdd"
      :title="'一般车辆备件类型保修期新增'"
      width="850px"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <AddForm @close="closeAdd" @save="saveAdd"></AddForm>
    </BaseDialog>
    <BaseDialog
      :visible.sync="visibleEdit"
      :title="'一般车辆备件类型保修期编辑'"
      width="850px"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <EditForm :rowData="rowData" @close="editclose" @save="editsave"></EditForm>
    </BaseDialog>
    <BaseDialog :visible.sync="showImport" :closable="false" icon="el-icon-upload" title="导入" width="800px" destroyOnClose :containerStyle="{ height: 'calc(100% - 120px)', overflow: 'auto', paddingBottom: '60px' }">
      <importExcel @close="showImport = false" @importclose="editsave1()" :url='`${uploadUrl}/api/cms_claimfac/rPCommonPt/importExcel`'/>
    </BaseDialog>
  </div>
  </Spin>
</template>
<script>
import { getToken, getAppId, getUserId } from '@/assets/js/auth';
import { getListByPage, newSave, piliangqiyong, piliangtingyong, excelExport, editSave, downloadModel, getListForExport, getPartType,exporturl } from '@/api/claim/factory/GenerallyCarPartTypeWarrantyMaintain';
// import importYiBanCheLiangPeiJianLeiXingBaoXiuQiWeiHu from './importYiBanCheLiangPeiJianLeiXingBaoXiuQiWeiHu.vue';
import config from '@/assets/js/config';
import importExcel from '@/pages/claimDemage/tools/importExcel.vue';
import AddForm from './AddForm.vue';
import Vehicle from '@/pages/claimDemage/tools/ModelVehicle.vue';
import EditForm from './EditForm.vue';
import { exportExcelFile } from '@/utils/index';
import { getPart } from '@/api/dictionary/index';
import {dictionary} from'@/utils/dictMixin';

export default {
    props: {
    // rowData: {
    //   type: Object,
    //   default: () => ({})
    // }
  },
  mixins: [dictionary],
  components: {
    Vehicle,
    AddForm,
    EditForm,
    importExcel,
  },
  data() {
    return {
      dataList: [],
      rowData: {},
      params: {},
      visible: false,
      disableds: true,
      showImport: false,
      collapse: false,
      visibleEdit: false,
      fetchapi: getListByPage,
      topFilterInit: this.topFilterInitFun(),
      columns: this.creatHeader(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      dialogTitle: '选择车辆',
      visibleAdd: false,
      uploadUrl: config.uploadUrl,
      headersObj: {
        jwt: getToken(),
        appId: getAppId(),
        userId: getUserId(),
        userAgent: 'pc',
      },
      loading: false,
      loading1: false,
      fileList: [],
    };
  },
 created() {
  },
  methods: {
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      this.disableds = this.selectedRows.length <= 0;
    },
    // Excel更新导入
    showImportFun() {
      this.showImport = true;
    },
    //下载模板
    downloadTemplate() {
      this.$confirm('此操作将下载excel模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        downloadModel().then((res) => {
          console.log(res);
          exportExcelFile(res.data, '一般车辆备件类型保修期维护导入模板');
        });
      });
    },
    // 导出
    async exportFileBtn() {
      this.loading1 = true;
      getListForExport(this.fetchParams).then((res) => {
        exportExcelFile(res.data, '一般车辆备件类型保修期维护');
        this.loading1 =false;
      });
    },
    showErrorList(response) {
      if (response.resultCode == 200) {
        this.$notify.success({ title: '提示信息', message: '导入完成!' });
        this.fetchParams = { ...this.fetchParams };
        this.fileList = [];
        this.loading = false;
      } else {
        this.fileList = [];
        this.$notify.error({ title: '提示信息', message: response.errMsg });
        this.loading = false;
      }
    },
    handleExceed(error) {
      this.loading = false;
    },
    beforeUpload() {
      this.loading = true;
    },
    //批量启用
    async qiyong() {
      if (this.selectedRows.length > 0) {
        let str = '';
        this.selectedRows.map((x) => {
          str += x.ptId + ',';
        });
        const res = await piliangqiyong({ ids: str, status: '1' });
        this.fetchParams = { ...this.fetchParams };
      } else {
        return this.$notify.warning({ title: '提示信息', message: '请勾选后再进行启用！' });
      }
    },
    //批量停用
    async tingyong() {
      if (this.selectedRows.length > 0) {
        let str = '';
        this.selectedRows.map((x) => {
          str += x.ptId + ',';
        });
        const res = await piliangtingyong({ ids: str, status: '0' });
        this.fetchParams = { ...this.fetchParams };
        this.loading = false;
      } else {
        return this.$notify.warning({ title: '提示信息', message: '请勾选后再进行禁用！' });
      }
    },
    add() {
      this.visibleAdd = true;
    },
    closeAdd() {
      this.visibleAdd = false;
    },
    saveAdd() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    },
    editclose() {
      this.visibleEdit = false;
    },
    emitFun(val) {
      this.rowData = val;
      this.visibleEdit = true;
    },
    editsave() {
      this.visibleEdit = false;
      this.fetchParams = { ...this.fetchParams };
    },
    editsave1() {
      this.showImport = false;
      this.fetchParams = { ...this.fetchParams };
    },
    close() {
      this.visible = false;
    },
    chooseOrderNo() {
      this.visible = true;
    },
    save(obj) {
      this.visible = false;
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = Object.assign({}, this.fetchParams, val);
    },
    //搜索数据
    topFilterInitFun() {
      return [
        {
          type: 'INPUT',
          label: '保修期',
          fieldName: 'pRpairM',
          rules: [
            {
              validator: (rule, value, callback) => {
                if(value) {
                  if (Number.isInteger(Number(value))) {
                    callback();
                  } else {
                    callback(new Error('请输入数字值'));
                  }
                } else {
                  callback();
                }
              },
              trigger: ['blur', 'change'],
            },
          ],
          unitRender: () => {
            return <span>(月)</span>;
          },
          placeholder: '请输入保修期...',
          initialValue: '',
        },
        {
          type: 'INPUT',
          label: '保修里程',
          fieldName: 'pMile',
          rules: [
            {
              validator: (rule, value, callback) => {
                if(value) {
                  if (Number.isInteger(Number(value))) {
                    callback();
                  } else {
                    callback(new Error('请输入数字值'));
                  }
                } else {
                  callback();
                }
              },
              trigger: ['blur', 'change'],
            },
          ],
          unitRender: () => {
            return <span>(KM)</span>;
          },
          placeholder: '请输入保修里程...',
          initialValue: '',
        },
        {
          type: 'SELECT',
          label: '备件类型',
          fieldName: 'typeId',
          placeholder: '请选择备件类型...',
          itemList: [
            { text: '三电', value: '55091001' },
            { text: '整车', value: '55091002' },
            { text: '动力总成', value: '55091003' },
            { text: '特殊零部件', value: '55091004' },
            { text: '易损件1', value: '55091005' },
            { text: '易损件2', value: '55091006' },
            { text: '备件保修期1', value: '55091007' },
            { text: '备件保修期2', value: '55091008' }
          ],
          filterable: true
        },
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'pStatus',
          placeholder: '请选状态...',
          initialValue: '',
          itemList:[
            { text: '启用', value: 1 },
            { text: '禁用', value: 0 },
          ],
        },
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          fixed: 'left',
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          render: (props, h) => {
            return (
              <div style="text-align:center">
                <multiuse-button size="mini" type="text" onClick={() => this.emitFun(props.row)}>
                  编辑
                </multiuse-button>
              </div>
            );
          },
        },
        { title: '备件类型', dataIndex: 'typeName', sorter: true },
        { title: '适用车型', dataIndex: 'seriesName', sorter: true },
        { title: '营运类型', dataIndex: 'ptName', sorter: true },
        { title: '保修期（月）', dataIndex: 'pRpairM', sorter: true, width: 120 },
        { title: '保修里程（KM）', dataIndex: 'pMile', sorter: true, width: 120 },
        { title: '状态', dataIndex: 'pStatusStr', sorter: true },
        { title: '创建人', dataIndex: 'createdBy', sorter: true },
        { title: '创建时间', dataIndex: 'createdAt', sorter: true },
        { title: '修改人', dataIndex: 'updatedBy', sorter: true },
        { title: '修改时间', dataIndex: 'updatedAt', sorter: true },
      ];
    },
  },
};
</script>

<style lang="less" scoped></style>
